package com.oraro.paygatewaybiz.utils;

import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.oraro.paygatewaybiz.dto.PayOrderParam;
import com.oraro.paygatewaybiz.module.entity.OrderEntity;
import lombok.extern.slf4j.Slf4j;


import java.util.HashMap;
import java.util.Map;

/**
 * @Author: jianghuiyong
 * @Date: 2018/11/19 18:06
 * @Version 1.0
 */
@Slf4j
public class OrderValidator {

    public static boolean orderParamValidate (PayOrderParam payOrderParam, String signKey) {
        Map<String, String> map = new HashMap<>();
        map.put("body", payOrderParam.getBody());
        map.put("mchId", payOrderParam.getMchId().toString());
        map.put("outTradeNo", payOrderParam.getOutTradeNo());
        map.put("nonceStr", payOrderParam.getNonceStr());
        map.put("subject", payOrderParam.getSubject());
        map.put("totalFee", payOrderParam.getTotalFee().toString());
        map.put("sign", payOrderParam.getSign());

        //验证token是否合法
        boolean isValid = false;
        try {
            isValid = WXPayUtil.isSignatureValid(map, signKey, WXPayConstants.SignType.HMACSHA256);
        } catch (Exception e) {
            log.error(e.toString());
            return false;
        }
        return isValid;
    }

    /**
     * 返回JSAPI Notify参数
     * @param orderEntity
     * @param signKey
     * @return
     * @throws Exception
     */
    public static Map<String, String> generateNotifyParam (OrderEntity orderEntity, String signKey) throws Exception {
        Map<String,String> map = new HashMap<>();
        map.put("mch_id", orderEntity.getMchId().toString());
        map.put("out_trade_no", orderEntity.getOutTradeNo());
        map.put("total_fee", orderEntity.getTotalFee().toString());
        map.put("sign_type", WXPayConstants.HMACSHA256);
        String sign = WXPayUtil.generateSignature(map, signKey, WXPayConstants.SignType.HMACSHA256);
        map.put("sign", sign);
        return map;
    }
}
